package main

import (
	"context"
	publishserver "hertz_demo/kitex/publish/kitex_gen/publishserver"
	"hertz_demo/orm/cache"
	"hertz_demo/orm/db"
)

// PublishServiceImpl implements the last service interface defined in the IDL.
type PublishServiceImpl struct{}

// PublishVideo implements the PublishServiceImpl interface.
func (s *PublishServiceImpl) PublishVideo(ctx context.Context, req *publishserver.PublishVideoRequest) (resp *publishserver.PublishVideoResponse, err error) {
	// TODO: Your code here...
	resp = new(publishserver.PublishVideoResponse)
	dbVideo := new(db.Video)
	dbVideo.Title = req.Video.Title
	dbVideo.PlayUrl = req.Video.PlayUrl
	dbVideo.CoverUrl = req.Video.CoverUrl
	dbVideo.UserId = req.Video.Author.ID
	err = db.DB.Model(&db.Video{}).Create(dbVideo).Error
	if err == nil {
		createTime := dbVideo.CreatedAt.Unix()
		cache.AddVideo2Feed(dbVideo.ID, createTime)
	}
	return
}

// GetPublishList implements the PublishServiceImpl interface.
func (s *PublishServiceImpl) GetPublishList(ctx context.Context, req *publishserver.GetPublishListRequest) (resp *publishserver.GetPublishListResponse, err error) {
	// TODO: Your code here...
	resp = new(publishserver.GetPublishListResponse)
	// var resultList []models.Video
	var dbVideoList []db.Video
	if err = db.DB.Model(&db.Video{}).Find(&dbVideoList, "user_id = ?", req.User.ID).Error; err != nil {
		return
	}
	var favouriteList []int64
	if err = db.DB.Model(&db.FavouriteRelation{}).Select("video_id").Where("user_id = ?", req.User.ID).Scan(favouriteList).Error; err != nil {
		return
	}
	for _, dbVideo := range dbVideoList {
		isFavourite := false
		for _, vid := range favouriteList {
			if vid == dbVideo.ID {
				isFavourite = true
				break
			}
		}
		video := publishserver.Video{
			ID:             dbVideo.ID,
			Author:         req.User,
			Title:          dbVideo.Title,
			PlayUrl:        dbVideo.PlayUrl,
			CoverUrl:       dbVideo.CoverUrl,
			FavouriteCount: dbVideo.FavouriteCount,
			CommentCount:   dbVideo.CommentCount,
			IsFavourite:    isFavourite,
		}
		resp.ResultList = append(resp.ResultList, &video)
	}
	return
}
